<template>
  <div class="application-management">
    <!-- 头部 -->
    <div class="header">
      <div class="header-left">
        <i class="fas fa-arrow-left" @click="goBack"></i>
        <h3>开店申请管理</h3>
      </div>
      <div class="header-right">
        <div class="filter-tabs">
          <button
              v-for="tab in statusTabs"
              :key="tab.value"
              :class="['tab-btn', activeTab === tab.value ? 'active' : '']"
              @click="changeTab(tab.value)"
          >
            {{ tab.label }}
            <span class="tab-badge" v-if="tab.count > 0">{{ tab.count }}</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 申请列表 -->
    <div class="application-list">
      <div class="application-item" v-for="app in filteredApplications" :key="app.id">
        <div class="app-header">
          <h4>{{ app.businessName }}</h4>
          <span :class="['status', getStatusClass(app.status)]">
            {{ getStatusText(app.status) }}
          </span>
        </div>

        <div class="app-info">
          <p><strong>申请人:</strong> {{ app.applicant?.username || '未知' }}</p>
          <p><strong>地址:</strong> {{ app.businessAddress }}</p>
          <p><strong>联系方式:</strong> {{ app.contactInfo }}</p>
          <p><strong>申请时间:</strong> {{ formatDate(app.createdDate) }}</p>
          <p v-if="app.reviewComment"><strong>审核意见:</strong> {{ app.reviewComment }}</p>
        </div>

        <div class="app-actions">
          <button class="btn view-btn" @click="viewApplication(app.id)">查看详情</button>
          <button
              class="btn approve-btn"
              @click="reviewApplication(app.id, 1, app)"
              v-if="app.status === 0"
          >
            通过
          </button>
          <button
              class="btn reject-btn"
              @click="rejectApplication(app.id)"
              v-if="app.status === 0"
          >
            拒绝
          </button>
        </div>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-if="filteredApplications.length === 0">
        <i class="fas fa-clipboard-list"></i>
        <p>暂无申请数据</p>
      </div>
    </div>

    <!-- 审核对话框 -->
    <div class="modal" v-if="showRejectModal">
      <div class="modal-content">
        <h4>拒绝申请</h4>
        <textarea v-model="rejectReason" placeholder="请输入拒绝原因..." rows="4"></textarea>
        <div class="modal-actions">
          <button class="btn cancel-btn" @click="cancelReject">取消</button>
          <button class="btn confirm-btn" @click="confirmReject">确认拒绝</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { applicationAPI } from '@/api/application.js'
import { businessAPI } from '@/api/business.js'

const router = useRouter()

const applications = ref([])
const activeTab = ref('all')
const showRejectModal = ref(false)
const rejectReason = ref('')
const currentRejectId = ref(null)

const statusTabs = ref([
  { label: '全部', value: 'all', count: 0 },
  { label: '待审核', value: '0', count: 0 },
  { label: '已通过', value: '1', count: 0 },
  { label: '已拒绝', value: '2', count: 0 }
])

// 计算属性：筛选后的申请列表
const filteredApplications = computed(() => {
  if (activeTab.value === 'all') {
    return applications.value
  }
  return applications.value.filter(app => app.status === parseInt(activeTab.value))
})

// 页面加载时获取申请列表
onMounted(async () => {
  await loadApplications()
})

// 加载申请列表
const loadApplications = async () => {
  try {
    const response = await applicationAPI.getAllApplications()
    console.log('申请列表响应:', response)

    let data = null
    if (response.data && response.data.success === true && response.data.data) {
      data = response.data.data
    } else if (response.data) {
      data = response.data
    }

    if (data) {
      applications.value = data
    } else {
      applications.value = []
    }
    updateTabCounts()
  } catch (error) {
    console.error('获取申请列表失败:', error)
    alert('获取申请列表失败')
    applications.value = []
  }
}

// 更新标签计数
const updateTabCounts = () => {
  statusTabs.value.forEach(tab => {
    if (tab.value === 'all') {
      tab.count = applications.value.length
    } else {
      tab.count = applications.value.filter(app => app.status === parseInt(tab.value)).length
    }
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 切换标签
const changeTab = (tabValue) => {
  activeTab.value = tabValue
}

// 查看申请详情
const viewApplication = (applicationId) => {
  router.push(`/admin/applications/${applicationId}`)
}

// 审核通过
const reviewApplication = async (applicationId, status, application) => {
  const action = status === 1 ? '通过' : '拒绝'
  const comment = status === 1 ? '审核通过' : rejectReason.value

  if (!confirm(`确定要${action}这个开店申请吗？`)) {
    return
  }

  try {
    console.log('发送审核数据:', { status, reviewComment: comment })

    // 使用修正后的API调用
    const reviewResponse = await applicationAPI.reviewApplication(applicationId, status, comment)

    if (status === 1) {
      // 审核通过后，自动创建店铺
      await createBusinessFromApplication(application)
    }

    alert(`申请${action}成功`)
    await loadApplications() // 重新加载列表
  } catch (error) {
    console.error(`${action}申请失败:`, error)
    const errorMessage = error.response?.data?.message || error.message || `${action}申请失败`
    alert(`${action}申请失败：${errorMessage}`)
  }
}

// 根据申请创建店铺
const createBusinessFromApplication = async (application) => {
  try {
    const businessData = {
      businessName: application.businessName,
      businessAddress: application.businessAddress,
      businessExplain: application.businessDescription || '店铺描述',
      businessImg: application.businessImage || '',
      orderTypeId: application.orderTypeId || 1,
      startPrice: application.startPrice || 0,
      deliveryPrice: application.deliveryPrice || 0,
      remarks: `由开店申请自动创建，申请ID: ${application.id}`,
      applicantId: application.applicant.id // 添加申请人ID
    }

    console.log('创建店铺数据:', businessData)
    const response = await businessAPI.addBusiness(businessData)
    console.log('店铺创建成功:', response)

  } catch (error) {
    console.error('创建店铺失败:', error)
    alert('审核通过，但创建店铺时出现错误，请手动创建店铺。错误信息：' + (error.response?.data?.message || error.message))
  }
}

// 拒绝申请 - 确保函数名与模板中一致
const rejectApplication = (applicationId) => {
  currentRejectId.value = applicationId
  showRejectModal.value = true
  rejectReason.value = '' // 清空之前的拒绝原因
}

// 取消拒绝
const cancelReject = () => {
  showRejectModal.value = false
  rejectReason.value = ''
  currentRejectId.value = null
}

// 确认拒绝
const confirmReject = async () => {
  if (!rejectReason.value.trim()) {
    alert('请输入拒绝原因')
    return
  }

  try {
    console.log('发送拒绝数据:', { status: 2, reviewComment: rejectReason.value })

    // 使用修正后的API调用
    await applicationAPI.reviewApplication(currentRejectId.value, 2, rejectReason.value)
    alert('申请拒绝成功')
    showRejectModal.value = false
    rejectReason.value = ''
    currentRejectId.value = null
    await loadApplications() // 重新加载列表
  } catch (error) {
    console.error('拒绝申请失败:', error)
    const errorMessage = error.response?.data?.message || error.message || '拒绝申请失败'
    alert('拒绝申请失败：' + errorMessage)
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    0: 'pending',
    1: 'approved',
    2: 'rejected'
  }
  return classMap[status] || 'pending'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'})
}
</script>

<style scoped>
.application-management {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 10px;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left i {
  font-size: 20px;
  color: #666;
  cursor: pointer;
}

.header-left h3 {
  margin: 0;
  color: #333;
}

.filter-tabs {
  display: flex;
  gap: 5px;
  background: #f8f9fa;
  padding: 5px;
  border-radius: 8px;
}

.tab-btn {
  padding: 8px 16px;
  border: none;
  background: transparent;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s;
}

.tab-btn.active {
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.tab-badge {
  background: #ff4757;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 12px;
}

.application-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.application-item {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.app-header h4 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status.pending {
  background: #fff3cd;
  color: #856404;
}

.status.approved {
  background: #d4edda;
  color: #155724;
}

.status.rejected {
  background: #f8d7da;
  color: #721c24;
}

.app-info p {
  margin: 5px 0;
  color: #666;
}

.app-actions {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.view-btn {
  background: #6c757d;
  color: white;
}

.approve-btn {
  background: #28a745;
  color: white;
}

.reject-btn {
  background: #dc3545;
  color: white;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 10px;
  width: 400px;
  max-width: 90%;
}

.modal-content h4 {
  margin: 0 0 15px 0;
}

.modal-content textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  resize: vertical;
}

.modal-actions {
  display: flex;
  gap: 10px;
  margin-top: 15px;
  justify-content: flex-end;
}

.cancel-btn {
  background: #6c757d;
  color: white;
}

.confirm-btn {
  background: #dc3545;
  color: white;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #999;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 10px;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 15px;
  }

  .filter-tabs {
    flex-wrap: wrap;
  }

  .app-actions {
    flex-direction: column;
  }
}
</style>